<template>
  <div id="User">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top:15px">
      <el-row :gutter="12">
        <el-col :span="8">
          <div>
            <el-input
              placeholder="请输入内容"
              class="input-with-select"
              v-model="queryInfo.query"
              :clearable="true"
              @clear="getUserList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="success" @click="addDialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" style="width: auto" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱号"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑信息" placement="top">
              <el-button type="primary" icon="el-icon-edit" size="mini" v-model="scope.row" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除用户" placement="top">
              <el-button type="danger" icon="el-icon-delete" size="mini" v-model="scope.row" @click="showDelDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRight(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible" @close="addDialogClose">
      <el-form
      :model="addForm"
      :rules="FormRules"
      ref="addFormRef"
      label-width="auto"
      >
        <el-form-item label="添加用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="设置密码" prop="password">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="添加邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="添加手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改用户信息" :visible.sync="editDialogFormVisible" @close="editDialogClose">
      <el-form
      :model="editForm"
      :rules="FormRules"
      ref="editFormRef"
      label-width="auto"
      >
        <el-form-item label="用户名:">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(editForm.id)">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="delDialogVisible" width="30%">
      <span>您确定删除该用户吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delUser(delForm.id)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="setRightDialogViisble" width="40%" class="right">
      <div>
        <p>当前用户名称:{{userInfo.username}}</p>
        <p>当前用户角色:{{userInfo.role_name}}</p>
        <p>分配新角色:
          <template>
            <el-select v-model="sltRoleId" placeholder="请选择" clearable>
              <el-option
                v-for="item in userRoles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogViisble = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'User',
  data () {
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) return callback()
      callback(new Error('请输入一个合法的邮箱'))
    }
    const checkMobile = (rule, value, callback) => {
      const regEmail = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regEmail.test(value)) return callback()
      callback(new Error('请输入一个合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      userInfo: {},
      userRoles: [],
      sltRoleId: '',
      total: 0,
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      delDialogVisible: false,
      setRightDialogViisble: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {},
      delForm: {},
      FormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在3-10之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '用户名长度在6-16之间', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChange (userInfo) {
      console.log(userInfo)
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    addUser () {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return this.$message.error('请填入正确的信息')
        this.$http.post('users', this.addForm).then(res => {
          this.$message.success('添加用户成功')
          this.addDialogFormVisible = false
          this.getUserList()
        }, () => {
          this.$message.error('添加用户失败')
        })
      })
    },
    // async showEditDialog (id) {
    //   const { data: res } = await this.$http.get('users/' + id)
    //   if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
    //   this.editForm = res.data
    //   console.log(res.data)
    //   this.editDialogFormVisible = true
    // },
    showEditDialog (id) {
      this.$http.get('users/' + id).then(ret => {
        console.log(ret.data.data)
        this.editForm = ret.data.data
        this.editDialogFormVisible = true
      }, () => {
        this.$message.error('获取用户信息失败')
      })
    },
    showDelDialog (id) {
      this.$http.get('users/' + id).then(ret => {
        this.delForm = ret.data.data
        this.delDialogVisible = true
      }, () => {
        this.$message.error('服务器未响应')
      })
    },
    editUser (id) {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return this.$message.warning('含有非法字符，请重新输入')
        this.$http.put('users/' + id, this.editForm).then(res => {
          this.editDialogFormVisible = false
          this.$message.success('修改信息成功')
        }, () => {
          this.$message.error('修改信息失败')
        })
      })
    },
    delUser (id) {
      this.$http.delete('users/' + id).then(ret => {
        this.delDialogVisible = false
        this.getUserList()
        this.$message.success(ret.data.meta.msg)
      }, () => {
        this.$message.error('删除失败')
      })
    },
    setRight (Info) {
      this.sltRoleId = ''
      this.userInfo = Info
      this.setRightDialogViisble = true
      this.$http.get('roles').then(ret => {
        this.userRoles = ret.data.data
      }, () => {
        this.$message.error('服务器未响应')
      })
    },
    saveRoleInfo () {
      if (!this.sltRoleId) return this.$message.error('请选择一个新角色')
      this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.sltRoleId }).then(ret => {
        this.getUserList()
        this.setRightDialogViisble = false
      }, () => {
        this.$message.error('修改角色失败')
      })
    }
  }
}
</script>

<style Lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
}
.right div{
  text-align: left;
}
</style>
